/**
 * type 微信或支付宝
 id  下拉框id
 */
function findFirstType(type, flag) {
    $.ajax({
        cache: true,
        type: "get",
        url: baseURL + "onlineBusinessXDL/findFirstTypeList",
        data: {"type": type},
        async: false,
        dataType: "json",
        success: function (data) {
            var str = "<option value=''>请选择</option>";
            if (data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    str += "<option value='" + data[i].firstType + "'>" + data[i].firstType + "</option>";
                }
            }
            $("#firstType" + flag).html(str);
            $("#secondType" + flag).html("<option value=''>请选择</option>");
            $("#thirdType" + flag).html("<option value=''>请选择</option>");
            $("#bizId" + flag).val("");
        },
        error: function (data) {

        }
    });
}

function findSecondType(type, obj, flag) {

    var firstType = $(obj).val();
    $.ajax({
        cache: true,
        type: "get",
        url: baseURL + "onlineBusinessXDL/findSecondTypeList",
        data: {"type": type, "firstType": firstType},
        async: false,
        dataType: "json",
        success: function (data) {

            var str = "<option value=''>请选择</option>";
            if (data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    str += "<option value='" + data[i].secondType + "'>" + data[i].secondType + "</option>";
                }
            }
            $("#secondType" + flag).html(str);
            $("#thirdType" + flag).html("<option value=''>请选择</option>");
            $("#bizId" + flag).val("");
        },
        error: function (data) {

        }
    });
}

function findThirdType(type, obj, flag) {

    var secondType = $(obj).val();
    $.ajax({
        cache: true,
        type: "get",
        url: baseURL + "onlineBusinessXDL/findThirdTypeList",
        data: {"type": type, "secondType": secondType},
        async: false,
        dataType: "json",
        success: function (data) {
            var str = "<option value=''>请选择</option>";
            if (data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    str += "<option value='" + data[i].bizId + "'>" + data[i].thirdType + "</option>";
                }
            }
            $("#thirdType" + flag).html(str);
            $("#bizId" + flag).val("");
        },
        error: function (data) {

        }
    });
}
function findProvinceSPD() {
    $.ajax({
        cache: true,
        type: "post",
        url: baseURL + "XDLInfo/inToCode",
        data: {"provNm": "", "cityNm": ""},
        async: false,
        dataType: "json",
        success: function (result) {
            var data = result.province;
            //console.log(data)
            var str = "<option value=''>请选择</option>";
            if (data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    var da = data[i];
                    str += "<option value='" + data[i][1] + "'>" + data[i][0] + "</option>";
                }
            }
            $("#provinceSPD").html(str);
            var $area = $("#provinceSPD");
            if ($area.attr("areaCode")) {
                $area.val($area.attr("areaCode"));
                $area.change();
            }
        },
        error: function (data) {
        }
    });
}

function findCitySPD(obj) {
    var provNm = $("#provinceSPD option:selected").text();
    $.ajax({
        cache: true,
        type: "post",
        url: baseURL + "XDLInfo/inToCode",
        data: {"provNm": provNm, "cityNm": ""},
        async: false,
        dataType: "json",
        success: function (result) {
            var data = result.city;
            var str = "<option value=''>请选择</option>";
            if (data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    str += "<option value='" + data[i][1] + "'>" + data[i][0] + "</option>";
                }
            }
            $("#citySPD").html(str);
            var $area = $("#citySPD");
            if ($area.attr("areaCode")) {
                $area.val($area.attr("areaCode"));
                $area.change();
            }
        },
        error: function (data) {
        }
    });
}
function findDistrictSPD(obj) {
    var provNm = $("#provinceSPD option:selected").text();
    var cityNm = $("#citySPD option:selected").text();
    $.ajax({
        cache: true,
        type: "post",
        url: baseURL + "XDLInfo/inToCode",
        data: {"provNm": provNm, "cityNm": cityNm},
        async: false,
        dataType: "json",
        success: function (result) {
            var data = result.district;
            var str = "<option value=''>请选择</option>";
            if (data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    str += "<option value='" + data[i][1] + "'>" + data[i][0] + "</option>";
                }
            }
            $("#districtSPD").html(str);
            var $area = $("#districtSPD");
            if ($area.attr("areaCode")) {
                $area.val($area.attr("areaCode"));
                $area.change();
            }
        },
        error: function (data) {
        }
    });
}

$(document).ready(function () {
    // 初始化区域联动下拉框
    $("[name='areaDiv']").initAreaSelect();

    doBranchBank();
});

// 获取支行信息
function getBranchBank() {
    var cardProvince = $("#card\\.province").val(),
        cardCity = $("#card\\.city").val(),
        cardDistrict = $("#card\\.district").val(),
        cardNum = $("#card\\.cardNo").val();
    branchBankId = $('#card\\.branchBankId').attr('areaCode');


    $("#card\\.bankName").val('');
    $("#card\\.branchBankId").html('<option value="">请选择</option>');

    if (!cardProvince || !cardCity || !cardDistrict) {
        return;
    }
    if (checkBankCardLuhn(cardNum) != true) {
        return;
    }
    $.ajax({
        type: 'POST',
        url: baseURL + "bank/selectByProviceAndCity",
        data: {"provinceCode": cardProvince, "cityCode": cardCity, "countyCode": cardDistrict, "bankCardNo": cardNum},
        dataType: 'json',
        success: function (data) {
            $("#card\\.branchBankId").show();
            $("#card\\.branchBankName").prop('type', 'hidden');
            if (data && data.length > 0) {
                $('#card\\.bankName').val(data[0].bankName);
                var html_ = '<option value="">请选择</option>';
                $.each(data, function (i, item) {

                    //支行信息回显
                    if (branchBankId == item.id) {
                        html_ += '<option selected="selected" value=' + item.id + ' data-code=' + item.cnapsCode + '>' + item.subbranchBank + '</option>';
                    }
                    html_ += '<option value=' + item.id + ' data-code=' + item.cnapsCode + '>' + item.subbranchBank + '</option>';
                });
                $("#card\\.branchBankId").html(html_);
                $("#card\\.branchBankName").val('');
            } else {
                $("#card\\.branchBankId").hide();
                $("#card\\.branchBankId").val('');
                $("#card\\.branchBankName").prop('type', 'text');
            }
        }
    });
}

//处理支行信息
function doBranchBank() {
    $("#card\\.province").change(getBranchBank);
    $("#card\\.city").change(getBranchBank);
    $("#card\\.district").change(getBranchBank);
    $("#card\\.cardNo").change(getBranchBank);
    $("#card\\.bankName").click(getBranchBank);
}

function checkBankCardNo(type) {
    // 初始化区域联动下拉框
    $("#openAddress").initAreaSelect();
    $("#card\\.cardNo").val('');
    $("#card\\.bankName").val('');
    $("#card\\.branchBankId").val('');
    $("#card\\.branchBankId").html('');
    $("#card\\.branchBankName").val('');
    if (1 == type || '' == type) {
        $("#card\\.cardNo").addClass("checkBankCard");
        $("#card\\.branchBankId").show();
        $("#card\\.branchBankName").prop('type', 'hidden');
    }
    if (2 == type) {
        $("#card\\.cardNo").removeClass("checkBankCard");
        $("#card\\.branchBankId").hide();
        $("#card\\.branchBankName").prop('type', 'text');
    }
}


$(function () {

    $("#card\\.branchBankId").change(function () {
        $("#card\\.branchBankName").val($(this).find("option:selected").text())
        $('#cnapsCode').val($(this).find("option:selected").data('code'))
    })

    /* // 初始化区域联动下拉框
     $("[name='areaDiv']").initAreaSelect();
     doBranchBank();
     */
    function alarmFormatter(value, options, row) {
        return '<img src=' + value + ' style="width:50px;height:50px;" class="img-polaroid" />';
    };

    $("#jqGrid").jqGrid({
        url: baseURL + 'store/list',
        datatype: "json",
        colModel: [
            {
                label: '头像',
                name: 'url',
                width: 20,
                align: "center",
                sortable: false,
                editable: true,
                formatter: alarmFormatter
            },
            {label: 'id', name: 'id', width: 30, key: true},
            {label: '商户号', name: 'upMercId', width: 30},
            {label: '门店名称', name: 'name', width: 40},
            {label: '企业名称', name: 'merchantName', index: "merchant_name", width: 40},
            {label: '法人', name: 'legalperson', index: "legalPerson", width: 15},
            {label: '门店地址', name: 'address', idenx: 'address', width: 45},
            {label: '联系电话', name: 'mobilePhone', index: "mobile_phone", width: 35},
            {label: '备注', name: 'remarks', width: 35},
            {
                label: '审核状态',
                name: 'auditStatus',
                index: "audit_status",
                width: 20,
                formatter: function (value, options, row) {
                    if (value == 0) {
                        return '<span class="label label-danger">未审核</span>';
                    } else if (value == 1) {
                        return '<span class="label label-info">审核中</span>';
                    } else if (value == 2) {
                        return '<span class="label label-success">审核通过</span>';
                    } else if (value == 3) {
                        return '<span class="label label-warning">审核不通过</span>';
                    } else if (value == 4) {
                        return '<span class="label label-warning">提交未审核</span>';
                    } else {
                        return "";
                    }
                }
            },
            {label: '创建时间', name: 'insertDate', index: "insert_date", width: 40},
        ],
        viewrecords: true,
        height: 720,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        },
    });

});

//暂时没找到点击图片关闭弹出层
function imgShow(obj) {
    var img = $(obj).find("img")[0].src;
    // alert(img);
    $("#showimg").attr('src', img);
    layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        area: '800px',
        //  time: 3000,//3秒自动关闭
        skin: 'layui-layer-nobg', //没有背景色
        shadeClose: true,
        content: $("#imgId").html()
    });
}

var vm = new Vue({
    el: '#dcapp',
    data: {
        q: {
            name: null,
        },
        id: null,
        showList: 1,
        title: null,
        store: {},
        bankCard: {},
        options: [],
        identityCardImgList: '[]',
        identityCardImg: null,
        businessImgList: '[]',
        businessImg: null,
        bankCardImgList: '[]',
        bankCardImg: null,
        storeSignImgList: '[]',
        storeSignImg: null,
        openLicenseImgList: '[]',
        openLicenseImg: null,
        XDLMerInfo: {},
        provinceList: [],
        provinceList1: [],
        cityList: [],
        districtList: [],
        branchLsit: [],
        provinceCode: '',
        cityCode: '',
        districtCode: '',
        cityList1: [],
        districtList1: [],
        branchLsit1: [],
        provinceCode1: '',
        cityCode1: '',
        districtCode1: '',
        branchBankObj: null,
        bizTypeId: '',
    },
    created: function () {

    },
    methods: {
        onSelectedProvince: function () {
            this.cityList = getAreaList(vm.provinceCode);
            this.districtList = [];
            this.branchLsit = [];
            //联行号为空
            this.bankCard.cnapsCode = '';

        },
        onSelectedCity: function () {
            this.districtList = getAreaList(vm.cityCode);
            //卡号
            if (!(checkBankCardLuhn(this.bankCard.cardNo) != true)) {
                //银行卡正确
                console.log("卡号正确!");
                this.branchLsit = getBankList(this.provinceCode, this.cityCode, this.districtCode, this.bankCard.cardNo);
            }
            this.bankCard.cnapsCode = '';
        },
        onSelectedProvince1: function () {
            this.cityList1 = getAreaList(vm.provinceCode1);
            this.districtList1 = [];

        },
        onSelectedCity1: function () {
            this.districtList1 = getAreaList(vm.cityCode1);
        },
        onSelectedDistrict: function () {

        },
        onSelectedDistrict1: function () {

        },
        getBankInfo: function () {
            if (this.districtCode == '' || ((typeof(this.districtCode)) == "undefined")) {
                this.showMsg("请选择完整的开户地址!");
                return;
            }
            if ((checkBankCardLuhn(vm.bankCard.cardNo) != true)) {
                this.showMsg("请先输入正确银行卡!");
                return;
            }
            this.branchLsit = getBankList(this.provinceCode, this.cityCode, this.districtCode, this.bankCard.cardNo);
            if ((this.branchLsit).length > 0) {
                this.bankCard.bankName = (this.branchLsit)[0].bankName;
            }
        },

        selectedBank: function () {
            //开户行如果没有
            if (this.bankCard.bankName == null) {
                if (typeof((this.branchLsit)[0])=="undefined"){
                    this.bankCard.bankName = null;
                }else {
                    this.bankCard.bankName = (this.branchLsit)[0].bankName;
                }

            }
            if (this.branchBankObj != null) {
                console.log("有支行" + this.branchBankObj.id);
                this.bankCard.cnapsCode = this.branchBankObj.cnapsCode;
                this.bankCard.branchBankName = this.branchBankObj.branchBankName;
            }
        },

        //回显数据
        returnData: function () {
            this.provinceCode1 = vm.store.province;
            this.cityCode1 = vm.store.city;
            this.districtCode1 = vm.store.district;

            this.provinceCode = vm.bankCard.province;
            this.cityCode = vm.bankCard.city;
            this.districtCode = vm.bankCard.district;

            //获取数据库支行对象
            this.branchBankObj = getBranchBankObj(vm.bankCard.branchBankId);
            //联行号
            this.bankCard.cnapsCode = this.branchBankObj.cnapsCode;
            //开户行
            this.bankCard.bankName = this.branchBankObj.bankName;

            //地址列表
            vm.provinceList = getAreaList('0');
            this.cityList = getAreaList(vm.bankCard.province);
            this.districtList = getAreaList(vm.bankCard.city);

            vm.provinceList1 = getAreaList('0');
            this.cityList1 = getAreaList(vm.store.province);
            this.districtList1 = getAreaList(vm.store.city);
            //银行列表
            this.branchLsit = getBankList(this.provinceCode, this.cityCode, this.districtCode, this.bankCard.cardNo);
        },
        showMsg: function (str) {
            /*this.$notify({
             title: '警告',
             message: str,
             type: 'warning'
             });*/
            alert(str);
        },
        query: function () {
            vm.reload();
        },
        getSPDDetal: function () {
            var storeId = getSelectedRow();//选择一条
            vm.getStore(storeId);
            if (storeId == null) {
                return;
            }
            if (vm.store.auditStatus == 1) {
                alert("正在审核中,请勿重复操作!");
                return;
            }
            if (vm.store.auditStatus == 2) {
                alert("已通过审核,请勿重复操作!");
                return;
            }
            if (vm.store.auditStatus == 3) {
                alert("未通过审核,请修改相关资料!");
                return;
            }
            findProvinceSPD();
            findFirstType(1, "_w");
            $.ajax({
                type: "GET",
                url: baseURL + "XDLInfo/" + storeId + "/report",
                contentType: "application/json",
                async: false,
                success: function (r) {
                    vm.XDLMerInfo = r.result;
                }
            });
            vm.showList = 3;
            vm.title = "编辑进件";
        },

        getSPDUpdate: function () {
            var storeId = getSelectedRow();//选择一条
            if (storeId == null) {
                return;
            }
            vm.getStore(storeId);
            if (vm.store.auditStatus == 0) {
                alert("未提交审核 ,请先提交审核资料!");
                return;
            }
            findProvinceSPD();
            findFirstType(1, "_w");
            $.ajax({
                type: "GET",
                url: baseURL + "XDLInfo/" + storeId + "/report",
                contentType: "application/json",
                async: false,
                success: function (r) {
                    vm.XDLMerInfo = r.result;
                }
            });
            vm.showList = 4;
            vm.title = "修改进件资料";
        },
        saveSPDInfo: function () {
            vm.XDLMerInfo.stoeAreaCod = $("#districtSPD").val();
            vm.XDLMerInfo.mccCd = $("#thirdType_w").val();
            var url = "XDLInfo/inTo";
            var formJson = JSON.stringify(vm.XDLMerInfo);
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: formJson,
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function () {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        updateSPDInfo: function () {
            vm.XDLMerInfo.stoeAreaCod = $("#districtSPD").val();
            vm.XDLMerInfo.mccCd = $("#thirdType_w").val();

            var url = "XDLInfo/update";
            var formJson = JSON.stringify(vm.XDLMerInfo);
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: formJson,
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function () {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        update: function () {
            var storeId = getSelectedRow();//选择一条
            if (storeId == null) {
                return;
            }
            vm.getKind();
            vm.getStore(storeId);
            vm.showList = 2;
            vm.showDetal = false;
            vm.title = "编辑门店";
        },
        add: function () {
            var storeId = getSelectedRow();//选择一条
            if (storeId == null) {
                return;
            }
            vm.getKind();
            vm.getStore(storeId);
            vm.getBankCard(storeId);
            vm.storeSignImgList = '[]';
            vm.openLicenseImgList = '[]';
            vm.businessImgList = '[]';
            vm.identityCardImgList = '[]';
            vm.bankCardImgList = '[]';

            vm.storeSignImg = eval('(' + vm.storeSignImgList + ')');
            vm.openLicenseImg = eval('(' + vm.openLicenseImgList + ')');
            vm.businessImg = eval('(' + vm.businessImgList + ')');
            vm.identityCardImg = eval('(' + vm.identityCardImgList + ')');
            vm.bankCardImg = eval('(' + vm.bankCardImgList + ')');
            vm.initImg();
            // vm.getKind();
            // vm.store = {};
            vm.showList = 2;
            vm.title = "增加门店";

            this.returnData();
        },
        detal: function () {
            vm.getKind();
            vm.getStore(vm.id);
            vm.showList = 2;
            vm.title = "详情";
        },
        saveOrUpdate: function () {
            //门店信息
            vm.store.province = $("#cardProvince").val();
            vm.store.city = $("#cardCity").val();
            vm.store.district = $("#cardDistrict").val();

            vm.bankCard.province = $("#card\\.province").val();
            vm.bankCard.city = $("#card\\.city").val();
            vm.bankCard.district = $("#card\\.district").val();

            /*vm.bankCard.branchBankName = $("#card\\.branchBankName").val();*/
            vm.bankCard.branchBankName = this.branchBankObj.branchBankName;
            /* vm.bankCard.branchBankId = $("#card\\.branchBankId").val();*/
            vm.bankCard.branchBankId = this.branchBankObj.id;

            vm.store.identityCardImg = vm.identityCardImg;
            vm.store.businessImg = vm.businessImg;
            vm.store.bankCardImg = vm.bankCardImg;
            vm.store.storeSignImg = vm.storeSignImg;
            vm.store.openLicenseImg = vm.openLicenseImg;
            vm.store.bankCard = vm.bankCard;
            var url = "store/saveAuthStore";
            var formJson = JSON.stringify(vm.store);
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: formJson,
                // async: false,
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function () {
                            /*vm.reload();*/
                            window.location.href = baseURL + "modules/merchant/store/storeAuthList.html";
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        del: function () {
            var storeIds = getSelectedRows();
            if (storeIds == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "store/delete",
                    contentType: "application/json",
                    data: JSON.stringify(storeIds),
                    success: function (r) {
                        if (r.code === 0) {
                            alert('操作成功', function () {
                                vm.reload();
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },

        audit: function () {
            var storeIds = getSelectedRows();
            if (storeIds == null) {
                return;
            }
            $.ajax({
                type: "POST",
                url: baseURL + "XDLInfo/query",
                contentType: "application/json",
                data: JSON.stringify(storeIds),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function () {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        getStore: function (storeId) {
            $.ajax({
                type: "GET",
                url: baseURL + "store/info/" + storeId,
                async: false,
                success: function (r) {
                    vm.store = r.store;
                    vm.bizTypeId = vm.store.bizTypeId;
                    if (r.code === 500) {
                        alert(r.msg);
                    }
                }
            });

        },
        getKind: function () {
            $.ajax({
                type: 'POST',
                url: baseURL + "common/getKind",
                dataType: 'json',
                async: false, //默认为true 异步
                success: function (r) {
                    vm.options = r.result;
                }
            });
        },
        getBankCard: function (storeId) {
            $.ajax({
                type: 'POST',
                url: baseURL + "store/getBankCard/" + storeId,
                dataType: 'json',
                async: false, //默认为true 异步
                success: function (r) {
                    if (r.bankCard == null) {
                        vm.bankCard = {};
                    } else {
                        vm.bankCard = r.bankCard;
                    }
                }
            });
        },
        reload: function (event) {
            vm.showList = 1;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'key': vm.q.key},
                page: page
            }).trigger("reloadGrid");
        },
        initImg: function () {
            $("#upload_open").initWebUploader(vm.openLicenseImg, "openLicenseImg", 1, vm.store.id, vm.openLicenseImg.length);
            $("#upload_idCard").initWebUploader(vm.identityCardImg, "identityCardImg", 2, vm.store.id, vm.identityCardImg.length);
            $("#upload_business").initWebUploader(vm.businessImg, "businessImg", 1, vm.store.id, vm.businessImg.length);
            $("#upload_bankCard").initWebUploader(vm.bankCardImg, "bankCardImg", 1, vm.store.id, vm.bankCardImg.length);
            $("#upload_store").initWebUploader(vm.storeSignImg, "storeSignImg", 2, vm.store.id, vm.storeSignImg.length);
        },
    }
});
laydate.render({
    elem: '#busExpDt', //指定元素
    done: function (value) {
        vm.XDLMerInfo.busExpDt = value;
    }
});
laydate.render({
    elem: '#crpExpDtTmp', //指定元素
    done: function (value) {
        vm.XDLMerInfo.crpExpDtTmp = value;
    }
});
